package com.dianrui.moonfire.activity;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.adapter.SecretProtocolAdapter;
import com.dianrui.moonfire.event.OpenOrClose;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.JsonUtils;
import com.dianrui.moonfire.util.MyUtil;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.google.gson.JsonObject;
import com.tbit.tbitblesdk.Bike.TbitBle;
import com.tbit.tbitblesdk.Bike.model.BikeState;
import com.tbit.tbitblesdk.Bike.services.command.callback.StateCallback;
import com.tbit.tbitblesdk.protocol.callback.ResultCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 扫码后的车辆信息
 */
public class ScanInfoActivity extends BaseActivity {
    private BluetoothAdapter blueadapter;
    private String vehicleStatus;
    private String vehicleIds, devicenumbers, isRomotes;
    private Double lat;
    private Double lng;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.battery)
    TextView battery;
    @BindView(R.id.billing)
    TextView billing;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.start_car)
    Button startCar;
    @BindView(R.id.journey)
    TextView journey;

    @Override
    public int getContentViewId() {
        return R.layout.activity_scaninfo;
    }

    @Override
    public void initView() {
        TbitBle.initialize(ScanInfoActivity.this, new SecretProtocolAdapter());
        blueadapter = BluetoothAdapter.getDefaultAdapter();
        customInit(true);
        title.setText(getString(R.string.scan_info));
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                devicenumbers = bundle.getString("devicenumber");
                isRomotes = bundle.getString("isRomote");
                vehicleStatus = bundle.getString("vehicle_status");
                lat = bundle.getDouble("lat");
                lng = bundle.getDouble("lng");
            }
        }
        getInfoPrice();

    }

    @Override
    public void initData() {
    }

    private void getInfoPrice() {
        JsonObject detectionJson = new JsonObject();
        detectionJson.addProperty("number", devicenumbers);
        detectionJson.addProperty("is_remote", isRomotes);
        detectionJson.addProperty("member_id",SPUtils.getInstance().getString("member_id"));
        XHttpRequest.getInstance().postRequests(Url.CHECK_BIKE, detectionJson.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        if (isFinishing()) {
                            return;
                        }
                        final JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                String data = JsonUtils.getJsonStr(response, "data");
                                number.setText(JsonUtils.getJsonStr(data, "number"));
                                battery.setText(JsonUtils.getJsonStr(data, "battery"));
                                billing.setText(JsonUtils.getJsonStr(data, "billing"));
                                content.setText(JsonUtils.getJsonStr(data, "content"));
                                SPUtils.getInstance().put("area_id", JsonUtils.getJsonStr(data, "area_id"),true);
                                StringBuilder journeyBulider = new StringBuilder();
                                journeyBulider.append("预计行驶:").append(JsonUtils.getJsonStr(data, "journey"));
                                journey.setText(journeyBulider.toString());

                                address.setText(JsonUtils.getJsonStr(data, "city_path"));

                                vehicleIds = jsonObject.optJSONObject("data").optString("vehicle_id");
                                startCar.setEnabled(true);
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                                startCar.setEnabled(false);

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
                startCar.setEnabled(false);
            }
        });
    }


    @OnClick({R.id.back, R.id.start_car})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.start_car:
                unLock(vehicleIds, isRomotes);
                break;
            default:
                break;

        }
    }


    //立即解锁
    private void unLock(final String vehicleIds, final String isRomotes) {
        showLoadingDialog(getString(R.string.open_locking));
        JsonObject unlock = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            unlock.addProperty("member_id",SPUtils.getInstance().getString("member_id"));
        }
        unlock.addProperty("is_remote", isRomotes);
        unlock.addProperty("vehicle_id", vehicleIds);
        unlock.addProperty("app_type", "1");
        unlock.addProperty("device_type", MyUtil.getSystemBARND() + "  " + MyUtil.getSystemModel());
        unlock.addProperty("app_version", MyUtil.getAppInfo(ScanInfoActivity.this));
        unlock.addProperty("type", 0);
        unlock.addProperty("gps", lng + "," + lat);
        try {
            XHttpRequest.getInstance().postRequests(Url.UNLOCK, unlock.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) {
                    if (!StringUtils.isEmpty(result)) {
                        try {
                            if (isFinishing()) {
                                return;
                            }
                            final JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject) {
                                if (Constant.DATAFAILED.equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                  if ("0".equals(jsonObject.optJSONObject("data").optString("state"))) {
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                    } else if ("1".equals(jsonObject.optJSONObject("data").optString("state"))) {//1是未认证
                                        Intent intent = new Intent(ScanInfoActivity.this, AuthActivity.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putString("isBackAuth", "1");
                                        intent.putExtras(bundle);
                                        startActivity(intent);
                                    } else if ("2".equals(jsonObject.optJSONObject("data").optString("state"))) {//2是未交押金
                                        Intent intent = new Intent(ScanInfoActivity.this, DepositActivity.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putString("isDespoitBack", "1");
                                        bundle.putString("isborrowCar", "1");
                                        bundle.putString("setting_id", jsonObject.optJSONObject("data").optString("setting_id"));
                                        intent.putExtras(bundle);
                                        startActivity(intent);
                                    } else if ("3".equals(jsonObject.optJSONObject("data").optString("state"))) {//3是跳转违章记录
                                        startActivity(new Intent(ScanInfoActivity.this, ViolationListActivity.class));
                                    } else if ("4".equals(jsonObject.optJSONObject("data").optString("state"))) {//4是跳转充值界面
                                        startActivity(new Intent(ScanInfoActivity.this, RechargeActivity.class));
                                    }else {
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                    }
                                }else if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    if (jsonObject.optJSONObject("data").optInt("type") == 0) {
                                        ToastUtil.showToast(jsonObject.optString("message"));
                                        EventBus.getDefault().post(new OpenOrClose(true));
                                        Intent intent = new Intent(ScanInfoActivity.this, RidingActivity.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putString("vehicle_id", vehicleIds);
                                        bundle.putString("isPlay", "1");
                                        bundle.putString("order_id", jsonObject.optJSONObject("data").optString("order_id"));
                                        bundle.putString("number", jsonObject.optJSONObject("data").optString("number"));
                                        bundle.putString("vehicle_status", vehicleStatus);
                                        intent.putExtras(bundle);
                                        startActivity(intent);
                                        finish();
                                    }else if (jsonObject.optJSONObject("data").optInt("type") == 1) {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(ScanInfoActivity.this, R.style.activity_dialog);
                                        View view = LayoutInflater.from(ScanInfoActivity.this).inflate(R.layout.blue_endcar_dialog, null);
                                        final AlertDialog dialog = builder.create();
                                        dialog.setView(view);
                                        dialog.show();
                                        final TextView contents = view.findViewById(R.id.content);
                                        final Button endBtn = view.findViewById(R.id.start_cars);
                                        final Button cancel = view.findViewById(R.id.cancel);
                                        contents.setText(jsonObject.optString("message"));
                                        cancel.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                dialog.dismiss();
                                            }
                                        });
                                        endBtn.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (!blueadapter.isEnabled()) {
                                                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                                                    ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                                                } else {
                                                    dialog.dismiss();
                                                    showLoadingDialog("正在连接蓝牙中,请稍候...");
                                                    connectBlueTeeth(jsonObject.optJSONObject("data").optString("device"),jsonObject.optJSONObject("data").optString("token"),jsonObject.optJSONObject("data").optString("order_id"));
                                                }

                                            }
                                        });
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                    dismissLoadingDialog();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    // 连接，参数为设备编号，密钥（后台提供）
    private void connectBlueTeeth(String deviceNumber, String key, final String orderid) {
        TbitBle.connect(deviceNumber, key, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 连接回应
                Log.e("连接成功后回应状态码-->", resultCode + "");
                if (resultCode == 0) {
                    unlockDevice(orderid);
                } else {
                    dismissLoadingDialog();
                    ToastUtil.showToast( "蓝牙借车失败，请重新再试");
                }
            }
        }, new StateCallback() {
            @Override
            public void onStateUpdated(BikeState bikeState) {

            }
        });

    }


    // 解锁
    private void unlockDevice(final String orderId) {
        TbitBle.unlock(new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                dismissLoadingDialog();
                if (resultCode==0){
                    BlueopenLock(orderId);
                }else {
                    ToastUtil.showToast("蓝牙操作失败，请稍候再试");
                }
            }
        });
    }


    private void BlueopenLock(final String orderid) {
        showLoadingDialog(getString(R.string.open_locking));
        JsonObject unlock = new JsonObject();
        unlock.addProperty("order_id", orderid);
        unlock.addProperty("status", "1");
        XHttpRequest.getInstance().postRequests(Url.BLUEUNLOCKUNLOCK, unlock.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                EventBus.getDefault().post(new OpenOrClose(true));
                                Intent intent = new Intent(ScanInfoActivity.this, RidingActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("vehicle_id", vehicleIds);
                                bundle.putString("isPlay", "1");
                                bundle.putString("order_id", jsonObject.optJSONObject("data").optString("order_id"));
                                bundle.putString("number", jsonObject.optJSONObject("data").optString("number"));
                                bundle.putString("vehicle_status", vehicleStatus);
                                intent.putExtras(bundle);
                                startActivity(intent);
                                finish();
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                if ("0".equals(jsonObject.optJSONObject("data").optString("state"))) {
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                } else if ("1".equals(jsonObject.optJSONObject("data").optString("state"))) {//1是未认证
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                    Intent intent = new Intent(ScanInfoActivity.this, AuthActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("isBackAuth", "1");
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                } else if ("2".equals(jsonObject.optJSONObject("data").optString("state"))) {//2是未交押金
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                    Intent intent = new Intent(ScanInfoActivity.this, DepositActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("isDespoitBack", "1");
                                    bundle.putString("isborrowCar", "1");
                                    bundle.putString("setting_id", jsonObject.optJSONObject("data").optString("setting_id"));
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                } else if ("3".equals(jsonObject.optJSONObject("data").optString("state"))) {//3是跳转违章记录
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                    JumpActivitys(ViolationListActivity.class);
                                } else if ("4".equals(jsonObject.optJSONObject("data").optString("state"))) {//4是跳转充值界面
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                    JumpActivitys(RechargeActivity.class);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }
}
